##########################################################################################

library(data.table)
library(optparse)
library(dplyr)
library(ggplot2)
library(pheatmap)

##########################################################################################
option_list <- list(
    make_option(c("--cor_data_file"), type = "character"),
    make_option(c("--synergy_data_file"), type = "character"),
    make_option(c("--out_path"), type = "character") 
)

if(1!=1){
    
    ## 相关性的文件
    cor_data_file <- "~/20231121_singleMuti/results/celltype_plot/trajectory/positive/pct_0.25/motif_motif/germ.motif_cor-chromvar.tsv"

    ## 协同作用的文件
    synergy_data_file <- "~/20231121_singleMuti/results/celltype_plot/trajectory/positive/pct_0.25/motif_motif/germ.motif_synergy-chromvar.tsv"

    ## 输出
    out_path <- "~/20231121_singleMuti/results/celltype_plot/trajectory/positive/pct_0.25/motif_motif/"

}

###########################################################################################
parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

cor_data_file <- opt$cor_data_file
synergy_data_file <- opt$synergy_data_file
out_path <- opt$out_path

dir.create(out_path , recursive = T)

###########################################################################################
## 读入文件
cor_data <- read.table(cor_data_file, header = TRUE, row.names = 1, sep = "\t")
synergy_data <- read.table(synergy_data_file, header = TRUE, row.names = 1, sep = "\t")

###########################################################################################
## 配色
my_color_palette <- colorRampPalette(c("blue", "white", "red"))(200)
my_breaks <- c(seq(-14, 0, length.out = 101), seq(0.0000000001, 44, length.out = 100))

###########################################################################################
## 画图，按照协同作用聚类
p2<-pheatmap(synergy_data, color = my_color_palette, breaks = my_breaks)
sorted_data <- synergy_data[p2$tree_row$order, ]
rownames<-rownames(sorted_data)
cor_data<-cor_data[rownames,rownames]

p1<-pheatmap(cor_data, color = colorRampPalette(c("blue", "white", "red"))(200), breaks = seq(-1, 1, length.out = 201),
cluster_rows = FALSE, cluster_cols = FALSE)

pdf(paste0(out_path,"/motif_cor-chromvar.pdf"),width = 24, height = 24)
print(p1)
dev.off()
pdf(paste0(out_path,"/motif_synergy-chromvar.pdf"),width = 24, height = 24)
print(p2)
dev.off()

